<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

use App\User;
use Str;
use Avatar;
use Storage;
class CreateDefaultAvatarJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 创建头像并保存
        $user = $this->user;
        $path = date('Y/md/');

        $realPath = 'users/avatar/' . $path;
        $filename = $user->id . '_' . time() . Str::random(10) . '.png';

        $avatar = Avatar::create($user->name)->getImageObject()->encode('png');

        Storage::put('/public/' . $realPath . $filename, $avatar);
        // 更新字段
        $user->avatar = '/storage/' . $realPath . $filename;
        $user->save();
    }
}
